package day12.handler.simpleChannelHandler.request;

import day12.handler.simpleChannelHandler.response.HeartBeatResponseHandler;
import day12.packet.request.HeartBeatRequestPacket;
import day12.packet.response.HeartBeatResponsePacket;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;

/**
 * @author chenshijie
 * @date 2024/1/6 14:36
 */
@ChannelHandler.Sharable
public class HeartBeatRequestHandler extends SimpleChannelInboundHandler<HeartBeatRequestPacket> {

    public static final HeartBeatRequestHandler INSTANCE = new HeartBeatRequestHandler();

    private HeartBeatRequestHandler() {

    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HeartBeatRequestPacket heartBeatRequestPacket) throws Exception {
        ctx.writeAndFlush(new HeartBeatResponsePacket());
    }

    // 该方法只有在没有idle方法的时候生效，否则不会走到这里。
    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent e = (IdleStateEvent) evt;
            if (e.state() == IdleState.READER_IDLE) {
                System.out.println("发送读心跳");
                ctx.writeAndFlush(new HeartBeatResponsePacket());
            } else if (e.state() == IdleState.WRITER_IDLE) {
                System.out.println("发送写心跳");
                ctx.writeAndFlush(new HeartBeatResponsePacket());
            } else {
                System.out.println("发送读写心跳");
                ctx.writeAndFlush(new HeartBeatResponsePacket());
            }
        }
    }

}
